package com.medica.ledproject.common;

import jakarta.servlet.http.HttpServletResponse;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author xiaona
 * @date 2024/5/29
 * @description TODO
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FileUtils  {

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.addHeader("Access-Control-Allow-Origin" , "*");
        response.addHeader("Access-Control-Expose-Headers" , "Content-Disposition,download-filename");
        response.setHeader("Content-disposition" , contentDispositionValue.toString());
        response.setHeader("download-filename" , percentEncodedFileName);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+" , "%20");
    }

    /**
     * 本地文件上传
     * @param file
     * @return
     */
    public static String uploadfile(MultipartFile file,String filePath,int type) {
        //创建时间文件夹
        String format = new SimpleDateFormat("yyyyMMdd").format((new Date()));
        if(type==1){
            format+="//pic";
        }else{
            format+="//video";
        }
        File file1=new File(filePath,format);
        if(!file1.exists())  file1.mkdirs();

        System.out.println("文件地址："+file1.getAbsolutePath());
        //获取文件后缀
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String newFileNamePrefix = UUID.randomUUID().toString().replace("-", "")+
                new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String newFileName =newFileNamePrefix+"."+extension;
        //处理上传操作
        try {
            file.transferTo(new File(file1,newFileName));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        System.out.println("文件上传成功");
        return "/"+format+"/"+newFileName;
    }


    /**
     * 文件删除
     *
     */
    public static void deleteFile(MultipartFile file,String filePath){
        String path = filePath;
        path = path + file.getOriginalFilename();
        File fileDel = new File(path);
        boolean isOk = fileDel.exists();
        if(isOk){
            fileDel.delete();
        }
    }

}